extends Node2D


const Directions = [
	Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN
]


##  最大x轴位置
export var max_x : int = 3
export var height : int = 7
export (float, 0.0, 1.0) var ratio : float = 0.4
export var min_generate_count : int = 25


var current_pos : Vector2 = Vector2.ZERO
var pos_list : Dictionary = {}
var default = []
var connect_list = []


func _ready():
	# 默认位置
	for i in range(height):
		default.push_back(Vector2(0, i))
		default.push_back(Vector2(1, i))
	for p in default:
		pos_list[p] = true
	
	# 生成足够的数量
	var count = 0
	while (
		pos_list.size() < min_generate_count + default.size() && count < 10 
		|| count == 0
	):
		generate()
		count += 1
	
	# 添加节点
	var b_data = AddButton.by_list_add_to(pos_list.keys(), self)
	for p in default:
		if b_data.has(p):
			b_data[p].modulate = Color.red


## 生成
func generate():
	for p in default:
		current_pos = p
		if randf() < ratio:
			if p.x == 0:	# 左边
				move_next(Vector2.LEFT)
				for i in range(3):
					move_next()
		
		if randf() < ratio:
			if p.x == 1:	# 右边
				move_next(Vector2.RIGHT)
				for i in range(3):
					move_next()
	


##  移动到下一个位置
func move_next(dir=Vector2.INF):
	if dir == Vector2.INF:
		dir = Directions[randi() % Directions.size()]
	
	var d = {
		left = current_pos + Vector2.LEFT,
		right = current_pos + Vector2.RIGHT,
		up = current_pos + Vector2.UP,
		down = current_pos + Vector2.DOWN,
	}
	
	var list = [Vector2.LEFT, Vector2.RIGHT, Vector2.UP, Vector2.DOWN]
	if pos_list.has(d.left) || d.left.x < -max_x:
		list.erase(Vector2.LEFT)
	if pos_list.has(d.right) || d.right.x > max_x:
		list.erase(Vector2.RIGHT)
	if pos_list.has(d.up) || d.up.y < 0:
		list.erase(Vector2.UP)
	if pos_list.has(d.down):
		list.erase(Vector2.DOWN)
	
	if list.size() == 0:
		dir = Vector2.DOWN
	else:
		dir = list[randi() % list.size()]
	
	connect_list.push_back({
		from = current_pos,
		to = current_pos + dir,
	})
	current_pos = current_pos + dir
	pos_list[current_pos] = true
	


## 双击重新加载
func _input(event):
	if event is InputEventMouseButton:
		if event.doubleclick:
			if get_tree().reload_current_scene() != OK:
				printerr("重新加载时出现错误")
